import { useSearchParams, Navigate } from 'react-router-dom';
import { TOKEN_KEY, REFRESH_TOKEN_KEY } from './common/constants';
import axios from 'axios';

export function GithubCallback() {
  const [searchParams] = useSearchParams();
  const code = searchParams.get('code') ?? '';

  getAccessTokenAxios(code);

  return <Navigate to="/home" />;
}

function getAccessTokenAxios(code: string) {
  const baseUrl = window.location.origin;
  const redirect_uri = `${baseUrl}/gitee/callback?scope=user_info,projects`;
  const client_id = import.meta.env.VITE_GITEE_CLIENT_ID;
  const client_secret = import.meta.env.VITE_GITEE_CLIENT_SECRET;
  const url = `/auth/oauth/token?grant_type=authorization_code&code=${code}&client_id=${client_id}&redirect_uri=${redirect_uri}&client_secret=${client_secret}`;
  axios
    .post(url)
    .then((response) => {
      console.log(JSON.stringify(response.data));
      const access_token = response.data?.access_token;
      if (access_token !== undefined && access_token !== '') {
        localStorage.setItem(TOKEN_KEY, access_token);
      }
      const refresh_token = response.data?.fresh_token;
      if (refresh_token !== undefined && refresh_token !== '') {
        localStorage.setItem(REFRESH_TOKEN_KEY, refresh_token);
      }
      console.log('res:' + access_token);
    })
    .catch((err) => console.log(err));
}
